package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Voice;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@Service(version = "1.0.0")
public class TaoHuaApiImpl implements TaoHuaApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Voice receive(String gender) {
        Query query = Query.query(Criteria.where("gender").is(gender).and("isAcceptable").is(1)).with(Sort.by(Sort.Order.asc("created")));
        Voice voice = mongoTemplate.findOne(query, Voice.class);
        //更新此条记录的状态
        Query query1 = Query.query(Criteria.where("_id").is(voice.getId()));
        Update update = new Update();
        update.set("isAcceptable",0);
        mongoTemplate.updateFirst(query1,update,Voice.class);
        return voice;
    }


    @Override
    public String deliver(Voice voice) {

        if (null == voice){
            return null;
        }
        voice.setId(new ObjectId());
        voice.setIsAcceptable(1);
        voice.setCreated(System.currentTimeMillis());

        mongoTemplate.save(voice);
        return voice.getId().toHexString();
    }


}
